package com.bjut.vendormgrsys.web.rest;

import com.bjut.vendormgrsys.service.CompanyService;
import com.bjut.vendormgrsys.web.dto.other.CompanyInfo;
import com.bjut.vendormgrsys.web.dto.other.ResultCompanyInfo;
import com.bjut.vendormgrsys.web.dto.other.ResultCompanyInfoData;
import com.bjut.vendormgrsys.web.dto.Success;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
public class CompanyApiController implements CompanyApi {

    private static final Logger log = LoggerFactory.getLogger(CompanyApiController.class);

    private final CompanyService service;

    @org.springframework.beans.factory.annotation.Autowired
    public CompanyApiController(CompanyService service) {
        this.service = service;
    }

    @Secured("ROLE_ADMIN")
    public ResponseEntity<Success> companyCreatePost(@Parameter(in = ParameterIn.DEFAULT, required = true, schema = @Schema()) @Valid @RequestBody CompanyInfo body) {
        ResponseEntity<Success> successEntity;
        try {
            String id = service.findId();
            service.saveCompanyInfo(id, body);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.OK.value()).message("保存公司信息成功"), HttpStatus.OK);
        } catch (Exception e) {
            log.error("保存公司信息异常：", e);
            successEntity = new ResponseEntity<>(new Success().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("保存公司信息失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return successEntity;
    }

    public ResponseEntity<ResultCompanyInfo> companyFindGet() {
        ResponseEntity<ResultCompanyInfo> responseEntity;
        try {
            String id = service.findId();
            ResultCompanyInfoData data = service.findById(id);
            responseEntity = new ResponseEntity<>(new ResultCompanyInfo().code(HttpStatus.OK.value()).message("成功").data(data), HttpStatus.OK);
        } catch (Exception e) {
            log.error("查询公司信息异常：", e);
            responseEntity = new ResponseEntity<>(new ResultCompanyInfo().code(HttpStatus.INTERNAL_SERVER_ERROR.value()).message("查询公司信息失败：" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return responseEntity;
    }

}
